﻿using IOA.MES.TcpService.Models;
using IOA.MES.TcpService.SortService.Response;
using IOA.Utils;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Text;

namespace IOA.MES.TcpService.SortService
{
    public class SortServer : AppServer<SortSession, StringRequestInfo>
    {
        public SortServer() : base(new SortReceiveFilterFactory()) { }

        protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
        {
            this.NewRequestReceived += ElectricMeterServer_NewRequestReceived;
            return base.Setup(rootConfig, config);
        }

        private void ElectricMeterServer_NewRequestReceived(SortSession session, StringRequestInfo requestInfo)
        {
            var orignData = requestInfo.Body;
            Logger.Warn($"{session.RemoteEndPoint.ToString()} 接收报文：{orignData}");
            var stopWatcher = new Stopwatch();
            stopWatcher.Start();

            var request = new
            {
                ClientIpHost = session.RemoteEndPoint.Address.ToString(),
                Data = orignData
            };
            var message = string.Empty;
            try
            {
                var responseStr = new HttpHelper().PostJson($"{ConfigurationManager.AppSettings["ServerApiRoot"]}/api/SortServer/PlcHandle", request);
                Logger.Warn($"{session.RemoteEndPoint.ToString()} 请求Api：{JsonUtils.Serialize(request)}，Api返回：{responseStr}");
                var response = JsonUtils.Deserialize<BaseResponse<PlcHandleResponse>>(responseStr);
                message = response.Data.Data;
            }
            catch (Exception ex)
            {
                Logger.Fatal($"{session.RemoteEndPoint.ToString()} 处理报文异常，报文：{orignData}，异常信息：{ex.Message}", ex);
                message = $"MKA-ER00000-SN" + (orignData.Length < 15 ? "" : orignData.Substring(14, request.Data.Length - 14));
            }
            SendMessage(session, message);
            stopWatcher.Stop();
            Logger.Warn($"{session.RemoteEndPoint.ToString()} 报文处理耗时：{stopWatcher.ElapsedMilliseconds}，报文内容：{orignData}");
        }

        private void SendMessage(SortSession session, string message)
        {
            var buffer = Encoding.ASCII.GetBytes(message);
            session.Send(buffer, 0, buffer.Length);
            Logger.Warn($"{session.RemoteEndPoint.ToString()} 发送报文：{message}");
        }
    }
}
